package com.service.supply;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.excel.EasyExcel;
import com.common.DesUtils;
import com.common.StringUtils;
import com.common.easyui.EasyuiUtils;
import com.common.http.HttpResult;
import com.common.http.HttpStatus;
import com.common.model.Global;
import com.common.model.UserTypeEnum;
import com.common.spring.SpringMvcUtils;
import com.dao.supply.LoginMapper;
import com.dao.supply.UserMapper;
import com.model.supply.SupplyUserModel;
import com.model.sys.SysUser;

@Service
public class UserService {
	static final Logger logger = LoggerFactory.getLogger(UserService.class);

	@Autowired
	UserMapper userDao;
	@Autowired
	private LoginMapper loginMapper;

	/**
	 * 列表查询
	 *
	 * @param queryMap
	 * @return
	 */
	public HttpResult selectList(Map<String, Object> queryMap) {
		HttpResult httpResult = new HttpResult();
		EasyuiUtils.addPageNum(queryMap);
		EasyuiUtils.addFilter(queryMap);
		String userTypeString = SpringMvcUtils.getUserType();
		if (userTypeString.equals(UserTypeEnum.SupplyUser.getValue())) {
			SupplyUserModel sySupplyUserModel = SpringMvcUtils.getSupplyUser();
			queryMap.put("infId", sySupplyUserModel.getInfId());
		}
		List<SupplyUserModel> list = userDao.selectList(queryMap);
		int count = userDao.selectListCount(queryMap);
		httpResult.setRows(list);
		httpResult.setTotal(count);
		logger.info("selectList:{}", list);
		return httpResult;
	}

	/**
	 * 详情
	 * 
	 * @param
	 * @return
	 */
	public HttpResult selectInfor(String userId) {
		HttpResult httpResult = new HttpResult();
		SupplyUserModel userModel = userDao.load(userId);
		httpResult.setData(userModel);
		httpResult.setCode(HttpStatus.SUCCESS_CODE);
		return httpResult;
	}

	/**
	 * 保存
	 *
	 * @param
	 * @return
	 */
	@Transactional
	public HttpResult save(SupplyUserModel userModel) {
		if (userModel == null) {
			return HttpResult.error("参数不能为空");
		}
		try {
			userModel.setUserPwd(DesUtils.encrypt(userModel.getUserPwd()));
		} catch (IOException e) {
			return HttpResult.error(e.getMessage());
		} catch (Exception e) {
			return HttpResult.error(e.getMessage());
		}
		HttpResult httpResult = new HttpResult();
		int result = 0;
		if (!StringUtils.isNotNull(userModel.getUserId())) {
			// 校验用户账号是否存在
			SupplyUserModel supplyUserInfo = loginMapper.querySupplierUserInfoByParams(userModel.getUserAccout());
			if (supplyUserInfo != null) {
				return HttpResult.error("该用户账号已被注册！");
			}
			userModel.setUserId(UUID.randomUUID().toString());
			result = userDao.insert(userModel);
		} else {
			result = userDao.update(userModel);
		}
		if (result > 0) {
			httpResult.setMsg("保存成功！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("保存失败！");
		}
		return httpResult;
	}

	public HttpResult changePwd(Map<String, Object> map) {

		String loginname = (String) map.get("loginname");
		String pwd = (String) map.get("pwd1");
		HashMap<String, Object> hashMap = new HashMap<String, Object>();
		hashMap.put("userAccount", loginname);
		try {
			hashMap.put("userPwd", DesUtils.encrypt(pwd));
		} catch (Exception e1) {
			return HttpResult.error("密码不正确！");
		}
		List<SupplyUserModel> model = userDao.selectList(hashMap);
		if (model == null || model.size() == 0) {
			return HttpResult.error("密码不正确！");
		}
		String pwd2 = (String) map.get("pwd2");
		String pwd3 = (String) map.get("pwd3");
		if (!pwd2.equals(pwd3)) {
			return HttpResult.error("密码不一致!");
		}
		try {
			model.get(0).setUserPwd(DesUtils.encrypt(pwd2));
		} catch (Exception e) {
			return HttpResult.error(e.getMessage());
		}

		HttpResult httpResult = new HttpResult();
		int result = 0;
		result = userDao.update(model.get(0));
		if (result > 0) {
			httpResult.setMsg("保存成功！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("保存失败！");
		}
		return httpResult;
	}

	/**
	 * 删除
	 *
	 * @param
	 * @return
	 */
	public HttpResult delete(String userId) {
		if (!StringUtils.isNotNull(userId)) {
			return HttpResult.error("参数不能为空");
		}
		SupplyUserModel model = userDao.load(userId);
		if (!model.getStatus().equals(Global.NO + "")) {
			return HttpResult.error("非待提交状态，不可删除！");
		}
		HttpResult httpResult = new HttpResult();
		int result = userDao.delete(userId);
		if (result > 0) {
			httpResult.setMsg("删除成功！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("不存在此条数据！");
		}
		return httpResult;
	}

	/**
	 * 导出
	 * 
	 * @param queryMap
	 * @param response
	 */
	public void export(Map<String, Object> queryMap, HttpServletResponse response) {
		List<SupplyUserModel> list = userDao.selectList(queryMap);
		logger.info("export:{}", list);
		try {
			EasyExcel.write(response.getOutputStream(), SupplyUserModel.class).sheet("模板").doWrite(list);
		} catch (IOException e) {
			logger.error("导出错误:{}", e.getMessage());
		}

	}
}
